<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta charset="utf-8">
    <meta http-equiv="pragma" content="no-cache"/>
    <meta http-equiv="cache-control" content="max-age=604800"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="author" content="Bootstrap-ecommerce by Vosidiy">

    <link href="/images/favicon.ico" rel="shortcut icon" type="image/x-icon">

    <!-- jQuery -->
    <script src="/js/jquery-2.0.0.min.js" type="text/javascript"></script>

    <!-- Bootstrap4 files-->
    <script src="/js/bootstrap.bundle.min.js" type="text/javascript"></script>
    <link href="/css/bootstrap.css" rel="stylesheet" type="text/css"/>

    <!-- Font awesome 5 -->
    <link href="/fonts/fontawesome/css/fontawesome-all.min.css" type="text/css" rel="stylesheet">

    <!-- custom style -->
    <link href="/css/ui.css" rel="stylesheet" type="text/css"/>
    <link href="/css/responsive.css" rel="stylesheet" media="only screen and (max-width: 1200px)"/>
    <link href="/css/footerAdjust.css" rel="stylesheet"/>

    <!-- custom javascript -->
    <script src="/js/script.js" type="text/javascript"></script>
    <script src="/js/cal.js" type="text/javascript"></script>

    <title>购物车</title>

    <script th:inline="javascript">
        $(document).ready(function () {
            var commodityList = [[${commodityList}]];
            var shoppingCartItemList = [[${shoppingCartItemList}]];
            console.log(shoppingCartItemList);
            $(".myCheckbox").each(function () {//初始化复选框
                $(this).prop("checked", ($(this).attr("prevalue") === "true"));//字符串不能传值布尔值，先进行一个简单转换
            });

            function updateCartPrice() {
                var totalprice = 0;
                $(".price").each(function () {
                    if ($("#checkbox" + $(this).attr("commodity")).prop("checked"))
                         totalprice = calc.add(Number($(this).children("span").text()),totalprice);
                });
                $(".total-price").text("￥" + totalprice.toFixed(2));
            }

            function updateTotalPrice(commodityIndex) {//用于更新单项商品总价
                var priceControl = $(".price").filter("[commodity=" + commodityIndex + "]");
                var quantityControl = $(".comm-quantity-input").filter("[commodity=" + commodityIndex + "]");
                var totalprice = calc.mul(commodityList[commodityIndex].commPrice, quantityControl.val());//调用calc进行准确的乘法运算
                priceControl.children("span").text(totalprice.toFixed(2));
                updateCartPrice();
            }

            $(".myCheckbox").change(function () {
                console.log(String($(this).prop("checked")));
                var newVal = String($(this).prop("checked"));
                $(this).prop("checked", ($(this).attr("preValue") === "true"));
                var thisCheck = $(this);
                var commodityIndex = $(this).attr("commodity");
                $.ajax({
                    type: "post",
                    url: "/shoppingCart",
                    data: {
                        "userUid": [[${userUid}]],
                        "commUid": commodityList[commodityIndex].commUid,
                        "commQuantity": $(".cart-quantity input").filter("[commodity=" + commodityIndex + "]").val(),
                        "itemChecked": newVal
                    },
                    async: true,
                    success: function () {
                        thisCheck.prop("checked", (newVal === "true"));
                        thisCheck.attr("prevalue", newVal);
                        updateCartPrice();
                    }
                });
            });

            for (var i = 0; i < commodityList.length; i++) {
                updateTotalPrice(i);
            }

            $(".cart-quantity>.minus").click(function () {//按下减少键
                var numInput = $(this).siblings("input");//取得兄弟input元素
                if (numInput.val() == 1)
                    return;
                var newVal = Number(numInput.val()) - 1;
                numInput.val(newVal);
                numInput.change();
            });
            $(".cart-quantity>.plus").click(function () {
                var numInput = $(this).siblings("input");
                var newVal = Number(numInput.val()) + 1;
                numInput.val(newVal);
                numInput.change();
            });

            $(".cart-quantity input").change(function () {
                var newVal = Number($(this).val());//存储新值
                if (isNaN(newVal) || newVal % 1 != 0 || newVal < 1) {//新值合法性判断
                    $(this).val($(this).attr("prevalue"));
                    return;
                }
                $(this).val($(this).attr("prevalue"));//将值还原回旧值
                var commodityIndex = $(this).attr("commodity");
                var thisInput = $(this);//保存对象，用来传值给回调函数
                $.ajax({
                    type: "post",
                    url: "/shoppingCart",
                    data: {
                        "userUid": [[${userUid}]],
                        "commUid": commodityList[commodityIndex].commUid,
                        "commQuantity": newVal,
                        "itemChecked":String($(".myCheckbox").filter("[commodity="+commodityIndex+"]").prop("checked"))
                    },
                    async: true,
                    success: function () {
                        thisInput.val(newVal);
                        thisInput.attr("prevalue", newVal);
                        updateTotalPrice(commodityIndex);
                    }
                });
            });
        });
    </script>
    <style>
        .custom-checkbox .custom-control-input:checked ~ .custom-control-label::before {
            background-color: #ffc107;
        }
    </style>
</head>
<body>
<div th:replace="fragment::header"></div>


<div class="container main-content" >
    <div class="row" style="margin-top: 30px">
        <div class="col-md-12">
            <div class="card">
                <table class="table table-hover shopping-cart-wrap">
                    <thead class="text-muted">
                    <tr>
                        <th scope="col" width="60">选中</th>
                        <th scope="col">商品</th>
                        <th scope="col" width="180">数量</th>
                        <th scope="col" width="120">总价</th>
                        <th scope="col" class="text-right" width="300">操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr th:each="commodity,comStat:${commodityList}">
                        <td style="display: flex;justify-content: center;">
                            <div class="custom-control custom-checkbox">
                                <input th:prevalue="${shoppingCartItemList[comStat.index].itemChecked}" type="checkbox"
                                       class="custom-control-input myCheckbox" th:commodity="${comStat.index}"
                                       th:id="'checkbox'+${comStat.index}">
                                <label class="custom-control-label" th:for="'checkbox'+${comStat.index}"></label>
                            </div>
                        </td>
                        <td>
                            <figure class="media">
                                <div class="img-wrap"><img th:src="${commodity.commHeadImage}" class="img-thumbnail img-sm">
                                </div>
                                <figcaption class="media-body">
                                    <h6 style="white-space: normal" class="title text-truncate"
                                        th:text="${commodity.commName}">
                                        Product name goes here </h6>
                                    <dl class="dlist-inline small">
                                        <dt>型号：</dt>
                                        <dd th:text="${commodity.commVersion}">XXL</dd>
                                    </dl>
                                </figcaption>
                            </figure>
                        </td>
                        <td>
                            <div class="input-group input-group-sm cart-quantity" style="width: 100px;">
                                <div class="minus input-group-prepend">
                                    <button class="btn btn-outline-secondary" type="button">
                                        <span class="fa fa-chevron-left"></span>
                                    </button>
                                </div>
                                <input th:prevalue="${shoppingCartItemList[comStat.index].commQuantity}"
                                       th:attr="commodity=${comStat.index}" type="text"
                                       th:value="${shoppingCartItemList[comStat.index].commQuantity}"
                                       class="form-control comm-quantity-input"
                                       style="text-align: center;font-weight:bold;">
                                <span class="plus input-group-append">
                                    <button class="btn btn-outline-secondary" type="button">
                                        <span class="fa fa-chevron-right"></span>
                                    </button>
                                </span>
                            </div><!-- /input-group -->
                        </td>
                        <td>
                            <div class="price-wrap">
                                <var class="price" th:attr="commodity=${comStat.index}">￥<span>145</span></var>
                                <small class="text-muted"
                                       th:text="'单价：￥'+${#numbers.formatDecimal(commodity.commPrice,0,2)}">
                                    (USD5 each)
                                </small>
                            </div> <!-- price-wrap .// -->
                        </td>
                        <td class="text-right">
                            <form style="display: inline" method="post" action="/shoppingCart/delete">
                                <input type="hidden" name="commUid" th:value="${commodity.commUid}">
                                <button type="submit" class="btn btn-outline-danger"> × 移除商品</button>
                            </form>
                            <a th:href="'/commodity/Details/'+${commodity.commUid}" class="btn btn-outline-warning">
                                查看商品详情 </a>
                        </td>
                    </tr>
                    <tr th:if="${commodityList.size()==0}">
                        <td></td><td class="h6">你的购物车里什么也没有...</td><td></td><td></td><td></td>
                    </tr>
                    </tbody>
                </table>
            </div> <!-- card.// -->
        </div>

    </div>
    <div class="row" style="padding-top: 30px">
        <div class="offset-md-6 col-md-4 text-right">
            <span class=" text-muted">
                选中商品总价：
            </span>
            <p class="h2 total-price">
                ￥0
            </p>

        </div>
        <div class="col-md-2 text-right " style="display: flex;align-items: center;justify-content: center;">
            <a th:unless="${commodityList.size()==0}" href="/orderConfirm" class="btn btn-block btn-lg btn-success">
                购买选中
            </a>
            <a th:if="${commodityList.size()==0}" href="/#" class="btn btn-block btn-lg btn-success disabled">
                购买选中
            </a>
        </div>
    </div>


</div>


<div th:replace="fragment::footer"></div>
</body>


</html>